import {pullAll,clone} from 'lodash'
import {defineComponent, h, ref, watch} from 'vue'
import {Tree, DirectoryTree, Form} from "ant-design-vue";
export default defineComponent({
    name: "ExTree",
    props:{
        value:Array,
        directory:Boolean,
        uncheckParentValue:Boolean,
    },
    emits:['update:value'],
    setup(props,ctx){
        const formItemContext = Form.useInjectFormItemContext();
        watch(()=>props.value,value=>{
            formItemContext.onFieldChange()
        })
        const attrs = ctx.attrs
        const emit = ctx.emit
        const propsValue = clone(props.value)
        if(!attrs.checkStrictly && attrs.checkable){
            recursionCheckedKeys(attrs.treeData)
        }
        const selectedKeys = ref(propsValue)
        const checkedKeys = ref(propsValue)
        function recursionCheckedKeys(data,pid = []) {
            let count = 0
            data.forEach(item=>{
                if(props.value.indexOf(item[attrs.fieldNames.key]) > -1){
                    count++
                }
                if(item[attrs.fieldNames.children]){
                    pid.push(item[attrs.fieldNames.key])
                    recursionCheckedKeys(item[attrs.fieldNames.children],pid)
                }
            })
            if(count < data.length && pid){
                pullAll(propsValue,pid)
            }
        }
        function onCheck(checkedKeys,e) {
            if(attrs.checkStrictly){
                emit('update:value',checkedKeys.checked)
            }else{
                checkedKeys = checkedKeys.concat(e.halfCheckedKeys)
                emit('update:value',checkedKeys)
            }
        }
        function onSelect(selectedKeys) {
            emit('update:value',selectedKeys)
        }
        return {
            selectedKeys,
            onSelect,
            onCheck,
            checkedKeys,
        }
    },
    render(e){
        let props = Object.assign({
            onCheck:this.onCheck,
            onSelect:this.onSelect,
            selectedKeys:this.selectedKeys,
            "onUpdate:selectedKeys":value=>{
                this.selectedKeys = value
            },
            checkedKeys:this.checkedKeys,
            "onUpdate:checkedKeys":value=>{
                this.checkedKeys = value
            }
        },e.$attrs)
        return h(props.directory?DirectoryTree:Tree, props, e.$slots)
    }
})




